package com.hgkj.cloud.customer.controller;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import javax.annotation.Resource;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.ibatis.session.SqlSession;
import org.mybatis.spring.SqlSessionTemplate;
import org.mybatis.spring.SqlSessionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import com.hgkj.cloud.base.domain.AdminUser;
import com.hgkj.cloud.base.domain.EUser;
import com.hgkj.cloud.base.domain.SysTenants;
import com.hgkj.cloud.base.domain.TenantFrameworks;
import com.hgkj.cloud.base.domain.TenantUsers;
import com.hgkj.cloud.base.service.AdminUserService;
import com.hgkj.cloud.base.service.EUserService;
import com.hgkj.cloud.base.service.SysTenantsService;
import com.hgkj.cloud.base.service.TenantFrameworksService;
import com.hgkj.cloud.base.service.TenantUsersService;

import lombok.extern.slf4j.Slf4j;

@Slf4j
public class BaseController {

	private Logger logger = LoggerFactory.getLogger(this.getClass());

	@Autowired
	private TenantFrameworksService mTenantFrameworksService;

	@Autowired
	private SysTenantsService sysTenantsService;
	@Autowired
	private TenantUsersService tenantUsersService;
	@Autowired
	private EUserService eUserFeignService;
	@Autowired
	private AdminUserService adminUserService;

	@Resource
	protected SqlSessionTemplate sqlSessionTemplate;

	/**
	 * 查看当前组织结构下所有组织机构的id
	 *
	 * @return
	 */
	public List<Long> getFrameworkIdsByFatherId(Long framework_id, Long tenant_id) {
		List<Long> ids = new ArrayList<>();
		Map<String, Object> map = new HashMap<>();
		if (tenant_id != null)
			map.put("tenant_id", tenant_id);
		map.put("father_id", framework_id);
		List<TenantFrameworks> frameworks = mTenantFrameworksService.getFrameworkByMap(map);
		if (frameworks.size() > 0) {
			for (int i = 0; i < frameworks.size(); i++) {
				ids.addAll(getFrameworkIdsByFatherId(frameworks.get(i).getId(), tenant_id));
			}
		}
		ids.add(framework_id);
		return ids;
	}

	/**
	 * 大租户下级单位id集合
	 *
	 * @param tenantId
	 * @return
	 */
	public List<Long> getSonTenantIds(Long tenantId) {
		List<Long> ids = new ArrayList<Long>();
		List<SysTenants> tenantList = sysTenantsService.listSonTenants(tenantId);
		if (tenantList.size() > 0) {
			for (int i = 0; i < tenantList.size(); i++) {
				if (tenantList.get(i).getTenant_level() > 1) {
					ids.addAll(getSonTenantIds(tenantList.get(i).getId()));
				} else {
					ids.add(tenantList.get(i).getId());
				}
			}
		}
		if (tenantId != null)
			ids.add(tenantId);
		return ids;
	}

	public TenantUsers getUserInfoById(String user_id) {
		Map<String, Object> map = new HashMap<>();
		map.put("id", user_id);
		TenantUsers user = tenantUsersService.getUserInfo(map);
		return user;
	}

	/**
	 * 根据登陆单位获取统计深度
	 */
	public int getLevel(Long tenant_id) {
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("tenant_id", tenant_id);
		List<TenantFrameworks> frameworks = mTenantFrameworksService.getFrameworkByFatherid(map);
		int[] arr = new int[frameworks.size()];
		int a = 0;
		for (TenantFrameworks fra : frameworks) {
			String wholename = fra.getWhole_name();
			String[] array = wholename.split("/");
			// System.out.println(wholename+"中 /" + " 总共出现了：" + (array.length - 1) + "次");
			arr[a] = array.length - 1;
			a = a + 1;
		}
		// System.out.println(arr);
		int i, min, max;
		min = max = arr[0];
		for (i = 0; i < arr.length; i++) {
			System.out.print(arr[i] + " ");
			if (arr[i] > max) // 判断最大值
				max = arr[i];
			if (arr[i] < min) // 判断最小值
				min = arr[i];
		}
		// System.out.println("\n数组的最大值是："+max); // 输出最大值
		return max;
	}

//
	/**
	 * 根据层级获取单位组织机构集合
	 *
	 * @param tenantId
	 * @return
	 */
	public List<TenantFrameworks> getAnalyzeFrameworks(Long tenantId, int level) {
		List<TenantFrameworks> ids = new ArrayList<TenantFrameworks>();
		SysTenants tenant = sysTenantsService.getSimpleTenantById(tenantId);
		List<SysTenants> tenants = getAnalyzeTenants(tenant.getId(), tenant.getTenant_level() - 1);
		Map<String, Object> p_map = new HashMap<String, Object>();
		for (int i = 0; i < tenants.size(); i++) {
			p_map.put("father_id", 0);
			p_map.put("tenant_id", tenants.get(i).getId());
			TenantFrameworks framework = mTenantFrameworksService.getFrameworkByName(p_map);
			if (framework != null)
				ids.addAll(getSonFrameworks(framework.getId(), level - tenants.get(i).getTenant_level(), false));
		}
		return ids;
	}

	/**
	 * 根据层级获取单位集合
	 *
	 * @param tenantId
	 * @return
	 */
	public List<SysTenants> getAnalyzeTenants(Long tenantId, int level) {
		List<SysTenants> ids = new ArrayList<SysTenants>();
		if (level == 0)
			ids.add(sysTenantsService.getSimpleTenantById(tenantId));
		else {
			level--;
			List<SysTenants> tenantList = sysTenantsService.listSonTenants(tenantId);
			if (tenantList.size() > 0) {
				for (int i = 0; i < tenantList.size(); i++) {
					if (tenantList.get(i).getTenant_level() > 1) {
						ids.addAll(getAnalyzeTenants(tenantList.get(i).getId(), level));
					} else {
						ids.add(tenantList.get(i));
					}
				}
			}
		}
		return ids;
	}

	/**
	 * 根据层级获取单位组织机构集合
	 *
	 * @param frameworkId
	 * @return
	 */
	public List<TenantFrameworks> getSonFrameworks(Long frameworkId, int level, boolean statUserCount) {
		List<TenantFrameworks> ids = new ArrayList<TenantFrameworks>();
		Map<String, Object> p_map = new HashMap<String, Object>();
		p_map.put("father_id", frameworkId);
		p_map.put("stat_user_count", statUserCount ? 1 : 0);
		if (level == 0) {
			ids.addAll(mTenantFrameworksService.getFrameworkByMap(p_map));
		} else {
			level--;
			List<TenantFrameworks> frameworks = mTenantFrameworksService.getFrameworkByMap(p_map);
			if (frameworks.size() > 0) {
				for (int i = 0; i < frameworks.size(); i++) {
					ids.addAll(getSonFrameworks(frameworks.get(i).getId(), level, statUserCount));
				}
			}
		}
		return ids;
	}

	protected Connection getConnection(SqlSession sqlSession) {
		Connection conn = null;
		try {
			conn = sqlSession.getConfiguration().getEnvironment().getDataSource().getConnection();
			System.out.print("===This Connection isClosed ? " + conn.isClosed());
		} catch (Exception e) {
			e.printStackTrace();
		}
		return conn;
	}

	protected SqlSession getNativeSqlSession() {
		return SqlSessionUtils.getSqlSession(sqlSessionTemplate.getSqlSessionFactory(),
				sqlSessionTemplate.getExecutorType(), sqlSessionTemplate.getPersistenceExceptionTranslator());
	}

	/**
	 * 关闭原生SqlSession 对应 getNativeSqlSession
	 *
	 * @return
	 */
	protected void closeNativeSqlSession(SqlSession sqlSession) {
		if (sqlSession != null)
			SqlSessionUtils.closeSqlSession(sqlSession, sqlSessionTemplate.getSqlSessionFactory());
	}

	public EUser getUserInfoByUuid(String user_uuid) {
		Map<String, Object> map = new HashMap<>();
		map.put("uuid", user_uuid);
		EUser user = eUserFeignService.getExamineUserInfo(map);
		return user;
	}

	public AdminUser getAdminUserInfoByUuid(String admin_uuid) {
		Map<String, Object> map = new HashMap<>();
		map.put("uuid", admin_uuid);
		AdminUser user = adminUserService.getAdminUserDataByMap(map);
		return user;
	}

	/**
	 * 通过treePath获取所有下级单位ID
	 *
	 * @param parentId 父级节点id
	 * @return {@link } List集合
	 */
	List<Long> getAllSonTenantFrameworksId(Long parentId) {
		ArrayList<Long> mTFIds = new ArrayList<>();
		mTFIds.add(parentId);
		TenantFrameworks tenantFrameworks = mTenantFrameworksService.getFrameworkById(parentId);
		Map<String, Object> map = new HashMap<>();
		map.put("tree_path", tenantFrameworks.getTree_path());
		List<TenantFrameworks> lists = mTenantFrameworksService.listAllFrameworkByMap(map);
		for (int i = 0; i < lists.size(); i++)
			mTFIds.add(lists.get(i).getId());
		return removeDuplicate(mTFIds);
	}

	public List<Long> removeDuplicate(List<Long> list) {
		List<Long> listTemp = new ArrayList();
		for (int i = 0; i < list.size(); i++) {
			if (!listTemp.contains(list.get(i))) {
				listTemp.add(list.get(i));
			}
		}
		return listTemp;
	}

	/**
	 * 获取所有上级单位ID
	 *
	 * @param sonId 父级节点id
	 * @return {@link } List集合
	 */
	List<Long> getAllFathersTenantFrameworksId(Long sonId) {
		ArrayList<Long> mTFIds = new ArrayList<>();
		TenantFrameworks frameworkById = mTenantFrameworksService.getFrameworkById(sonId);
		if (frameworkById != null) {
			if (!mTFIds.contains(frameworkById.getFather_id()))
				mTFIds.add(frameworkById.getFather_id());
			List<Long> list = getAllFathersTenantFrameworksId(frameworkById.getFather_id());
			if (list != null)
				mTFIds.addAll(list);

		}
		return mTFIds;
	}

//
//    void setLogs(AdminUser adminUserInfoByUuid, String operation, String module) {
//        TenantLogs tenantLogs = new TenantLogs();
//        tenantLogs.setUser_uuid(adminUserInfoByUuid.getUuid());
//        tenantLogs.setFramework_id(adminUserInfoByUuid.getFramework_id());
//        tenantLogs.setModule(module);
//        tenantLogs.setOperation(operation);
//        tenantLogsService.insert(tenantLogs);
//    }
//
	public void getframeworkDatas(Long framework_id, AdminUser operator, Map<String, Object> map) {
		List<Long> allTenantFrameworksIds;
		if (framework_id == null) {
			framework_id = operator.getFramework_id();
			allTenantFrameworksIds = getAllSubTenantFrameworkIdsByParent(framework_id, true);
			if (!operator.getChannel_id().equals("TOP"))
				map.put("framework_ids", allTenantFrameworksIds);
		} else {
			allTenantFrameworksIds = getAllSubTenantFrameworkIdsByParent(framework_id, true);
			map.put("framework_ids", allTenantFrameworksIds);
		}
	}

	public void getTreePathDatas(Long frameworkId, AdminUser operator, Map<String, Object> map) {
		if (frameworkId == null) {
			if (!operator.getChannel_id().equals("TOP")) {
				TenantFrameworks tenantFrameworks = mTenantFrameworksService
						.getFrameworkById(operator.getFramework_id());
				if (tenantFrameworks != null) {
					map.put("treePath", tenantFrameworks.getTree_path());
				}
			}
		} else {
			TenantFrameworks tenantFrameworks = mTenantFrameworksService.getFrameworkById(frameworkId);
			if (tenantFrameworks != null) {
				map.put("treePath", tenantFrameworks.getTree_path());
			}
		}
	}

	public void getTreePathDatas(Long frameworkId, Map<String, Object> map) {
		if (frameworkId != null) {
			TenantFrameworks tenantFrameworks = mTenantFrameworksService.getFrameworkById(frameworkId);
			if (tenantFrameworks != null) {
				map.put("treePath", tenantFrameworks.getTree_path());
			}
		}
	}

	public String encodeHtmlString(String xml) {
		String result = "";
		result = xml.replaceAll("\\'", "\\\\'");
		return result;
	}

	/**
	 * 查询当前机构及子机构ids
	 *
	 * @param parentId        机构id
	 * @param parentWholeName 机构全名
	 * @param level           层次，如果是999代表查询下面所有的，否则按层级返回子机构列表
	 * @param includeSelf     是否包含自己的机构信息
	 * @param extMap          扩展map，待用
	 * @return
	 */
	List<TenantFrameworks> getAllTenantFrameworksByParentAndLevel(Long parentId, String parentWholeName, int level,
			boolean includeSelf, Map<String, Object> extMap) {
		ArrayList<TenantFrameworks> list = new ArrayList<>();
		if (parentId == null && StringUtils.isBlank(parentWholeName)) {
			return list;
		}
		Map<String, Object> map = new HashMap<>();
		if (parentId != null) {
			map.put("parentId", parentId);
		} else {
			map.put("parentWholeName", parentWholeName);
		}
		map.put("level", level);
		map.put("includeSelf", includeSelf);
		if (extMap != null) {
			map.putAll(extMap);
		}
		return mTenantFrameworksService.listAllTenantFrameworksByParentAndLevel(map);
	}

	/**
	 * 查询当前机构及子机构ids
	 *
	 * @param parentId        机构id
	 * @param parentWholeName 机构全名
	 * @param level           层次，如果是999代表查询下面所有的，否则按层级返回子机构ids
	 * @param includeSelf     是否包含自己的机构信息
	 * @param extMap          扩展map，待用
	 * @return
	 */
	List<Long> getSubTenantFrameworkIdsByParentAndLevel(Long parentId, String parentWholeName, int level,
			boolean includeSelf, Map<String, Object> extMap) {
		List<TenantFrameworks> tenantFrameworks = getAllTenantFrameworksByParentAndLevel(parentId, parentWholeName,
				level, includeSelf, extMap);
		return CollectionUtils.isNotEmpty(tenantFrameworks)
				? tenantFrameworks.stream().map(TenantFrameworks::getId).collect(Collectors.toList())
				: new ArrayList<>();
	}

	/**
	 * 查询当前机构及子机构ids
	 *
	 * @param parentId    机构id
	 * @param includeSelf 是否包含自己的机构信息
	 * @return list
	 */
	List<Long> getAllSubTenantFrameworkIdsByParent(Long parentId, boolean includeSelf) {
		return getSubTenantFrameworkIdsByParentAndLevel(parentId, null, 999, includeSelf, null);
	}

	protected void IOclose(Connection conn, PreparedStatement pst, SqlSession nativeSqlSession) {
		try {
			if (pst != null) {
				pst.close();
			}
		} catch (SQLException ignored) {

		}
		try {
			if (conn != null) {
				conn.close();
			}
		} catch (SQLException ignored) {

		}
		try {
			if (nativeSqlSession != null) {
				closeNativeSqlSession(nativeSqlSession);
			}
		} catch (Exception ignored) {

		}
	}

}
